<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="title" label="标题" required>
				<uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="user_id" label="文章作者">
				<uni-easyinput placeholder="请输入作者名称" v-model="formData.user_id"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="content" label="文章内容" required>
				<!-- <uni-easyinput placeholder="文章内容" v-model="formData.content" trim="right"></uni-easyinput> -->
				<div id="content"></div>
			</uni-forms-item>
			<uni-forms-item name="project_id" label="问章分类">
				<uni-data-picker v-model="formData.project_id" collection="sys-project-categories"
					field="name as text,_id as value"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="view_count" label="阅读数量">
				<uni-easyinput placeholder="阅读数量" type="number" v-model="formData.view_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="avatar" label="封面大图">
				<uni-file-picker return-type="object" v-model="formData.avatar"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="article_status" label="文章状态">
				<uni-data-checkbox v-model="formData.article_status"
					:localdata="formOptions.article_status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="publish_date" label="发表时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-news-articles.js';
	import E from 'wangeditor';
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-news-articles';
	let editor = null;

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"title": "",
				"user_id": "",
				"content": "",
				"project_id": "",
				"view_count": 55,
				"avatar": null,
				"article_status": 0,
				"publish_date": null
			}
			return {
				formData,
				formOptions: {
					"article_status_localdata": [{
							"value": 0,
							"text": "草稿箱"
						},
						{
							"value": 1,
							"text": "已发布"
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.onLoadWangEdit()
		},
		methods: {

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.content = editor.txt.html();
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			onLoadWangEdit() {
				editor = new E('#content')
				editor.config.zIndex = 0

				editor.config.customUploadImg = function(resultFiles, insertImgFn) {
					// resultFiles 是 input 中选中的文件列表
					// insertImgFn 是获取图片 url 后，插入到编辑器的方法

					// 上传图片，返回结果，将图片插入到编辑器中
					resultFiles.forEach(item => {
						let path = URL.createObjectURL(item);
						let fileName = item.name + Date.now();
						uniCloud.uploadFile({
							filePath: path,
							cloudPath: fileName
						}).then(res => {
							console.log(res);
							insertImgFn(res.fileID)
						})
					})
				}

				editor.config.onblur = (newHtml) => {
					this.formData.content = newHtml
				};

				editor.create()
			}

		}
	}
</script>